package com.example.testapp.activity.activity.study;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testapp.R;
import com.example.testapp.activity.activity.SuperActivity;
import com.example.testapp.activity.model.User;
import com.example.testapp.activity.util.CharCheckUtil;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMSsoHandler;

import java.util.Map;
import java.util.Set;

/**
 * Created by l on 2016/9/1.
 */
public class LoginActivity extends SuperActivity {

    private View  view;
    private ImageView  mBackIV;
    private EditText   mPhoneET;
    private ImageView  mDeleteIV;
    private EditText   mCodeET;
    private TextView   mCodeGet;
    private TextView   mLoginTV;
    private ImageView  mCheckIV;

    private boolean flag = true;

    private int countSeconds = 60;  // 倒数秒数

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (countSeconds > 0){
                --countSeconds;
                mCodeGet.setText("发送验证码" + "(" + countSeconds + ")");
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }else{
                countSeconds = 60;
                mCodeGet.setText("发送验证码");
            }
        }
    };

    // 开始倒计时
    private void startCountBack() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCodeGet.setText(countSeconds + "");
                mHandler.sendEmptyMessage(0);
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = View.inflate(mContext, R.layout.activity_login, null);
        setContentView(view);
        initView();
    }

    private void initView() {
        mBackIV = (ImageView)view.findViewById(R.id.exit);
        mPhoneET = (EditText)view.findViewById(R.id.input_phone);
        mCodeET = (EditText)view.findViewById(R.id.code);
        mDeleteIV = (ImageView)view.findViewById(R.id.input_delete);
        mCodeGet = (TextView)view.findViewById(R.id.get_code);
        mLoginTV = (TextView)view.findViewById(R.id.login);
        mCheckIV = (ImageView)view.findViewById(R.id.check);
        mDeleteIV.setVisibility(View.GONE);
        mBackIV.setOnClickListener(mOnClickListener);
        mDeleteIV.setOnClickListener(mOnClickListener);
        mCodeGet.setOnClickListener(mOnClickListener);
        mLoginTV.setOnClickListener(mOnClickListener);
        mCheckIV.setOnClickListener(mOnClickListener);
        this.findViewById(R.id.user_tx).setOnClickListener(mOnClickListener);
        this.findViewById(R.id.user_ll).setOnClickListener(mOnClickListener);
        this.findViewById(R.id.login_qq).setOnClickListener(mOnClickListener);
        this.findViewById(R.id.login_weibo).setOnClickListener(mOnClickListener);

        mPhoneET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                  if (s.toString().length() > 0){
                       mDeleteIV.setVisibility(View.VISIBLE);
                  }else{
                       mDeleteIV.setVisibility(View.GONE);
                  }
            }
        });
    }

   public View.OnClickListener mOnClickListener = new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           switch (v.getId()){
               case R.id.exit:
                   finish();
                   break;
               case R.id.input_delete:
                   mPhoneET.setText("");
                   mDeleteIV.setVisibility(View.GONE);
                   break;
               case R.id.get_code:  // 获取手机号发送请求向手机发送验证码
                   hideSoftInput(LoginActivity.this, mPhoneET);
                   if (countSeconds != 60){
                       showToast("您的验证码已发送!");
                       return;
                   }
                   String phoneStr = mPhoneET.getText().toString();
                   if (CharCheckUtil.isPhoneNum(phoneStr)){
                       showProgressDialog();
                       showToast("发送成功");
                       startCountBack();
                   }else {
                       showToast("输入的手机号码有误!");
                   }
                   break;
               case R.id.login:
                   hideSoftInput(LoginActivity.this, mCodeET);
                   if (LoginCheck()){
                       User user = new User();
                       user.name = "咨询爱好者!";
                       user.uId = "111842201";
                       user.gender = 1;
                       user.birthday = System.currentTimeMillis() / 1000;
                       user.phone = mPhoneET.getText().toString();
                       Toast.makeText(mContext, "您好，" + user.name, Toast.LENGTH_SHORT).show();
                       mUserController.saveUserInfo(user);
                       Intent intent = new Intent(mContext, MyInfoActivity.class);
                       startActivity(intent);
                       finish();
                   }
                   break;
               case R.id.check:  //是否勾选用户协议
                   if (flag){
                       flag = false;
                       mLoginTV.setEnabled(false);
                       mLoginTV.setBackgroundResource(R.color.C8C8C8);
                       mCheckIV.setImageResource(R.mipmap.check_2);
                   }else{
                       flag = true;
                       mLoginTV.setEnabled(true);
                       mLoginTV.setBackgroundResource(R.color.white);
                       mCheckIV.setImageResource(R.mipmap.check_1);
                   }
                   break;
               case R.id.user_tx:

                   break;
               case R.id.user_ll:

                   break;
               case R.id.login_qq:  //QQ登录
                   QQLogin(SHARE_MEDIA.QQ);
                   break;
               case R.id.login_weibo:  //微博登录
                   SinaLogin(SHARE_MEDIA.SINA);
                   break;
               default:
                   break;
           }
       }
   };

    /**
     * QQ登录
     * @param platform
     */
    private void QQLogin(SHARE_MEDIA platform) {
        final UMSocialService mController = mShareUtils.getmController();
        mController.doOauthVerify(this, platform, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(Bundle bundle, SHARE_MEDIA platform) {
                String uid = bundle.getString("uid"); // 获取uid
                final User  qqUser = new User();
                qqUser.qqId = uid;
                if (!TextUtils.isEmpty(uid)){
                    //获取相关授权信息
                    mController.getPlatformInfo(mContext, platform, new UMDataListener() {
                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onComplete(int status, Map<String, Object> info) {
                            if (status == 200 && info != null){
                                StringBuilder sb = new StringBuilder();
                                Set<String>  keys = info.keySet();
                                for (String key : keys){
                                    sb.append(key + "=" + info.get(key).toString());
                                }
                                Log.d("TestData",sb.toString());
                                qqUser.name = info.get("screen_name").toString();
                                if (info.get("gender").toString().equals("男")){
                                    qqUser.gender = 1;
                                }else if (info.get("gender").toString().equals("女")){
                                   qqUser.gender = 2;
                                }else{
                                    qqUser.gender = 0;
                                }
                                qqUser.picUrl = info.get("profile_image_url").toString();
                                qqUser.city = info.get("city").toString();
                                qqUser.province = info.get("province").toString();

                                Toast.makeText(mContext, "您好," + qqUser.name, Toast.LENGTH_SHORT).show();
                                mUserController.saveUserInfo(qqUser);
                                Intent intent = new Intent(mContext, MyInfoActivity.class);
                                startActivity(intent);
                                finish();
                            }else{
                                Log.d("TestData","发生错误："+status);
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA share_media) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {

            }
        });
    }

    /**
     * Sina登录
     * @param platform
     */
    private void SinaLogin(SHARE_MEDIA platform) {
        final UMSocialService mController = mShareUtils.getmController();
        mController.doOauthVerify(LoginActivity.this, platform, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                final User sinaUser = new User();
                if (value != null && !TextUtils.isEmpty(value.getString("uid"))){
                    Toast.makeText(mContext, "授权成功", Toast.LENGTH_SHORT).show();
                    String uid = value.getString("uid"); // 获取uid
                    sinaUser.sinaId = uid;
                    //获取相关授权信息
                    mController.getPlatformInfo(mContext, platform, new UMDataListener() {
                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onComplete(int status, Map<String, Object> map) {
                            if (status == 200 && map != null){
                                StringBuilder sb = new StringBuilder();
                                Set<String> keys = map.keySet();
                                for(String key : keys){
                                    sb.append(key+"="+map.get(key).toString()+"\r\n");
                                }
                                Log.d("TestData",sb.toString());
                                sinaUser.name = map.get("screen_name").toString();
                                if (map.get("gender").toString().equals("1")){
                                    sinaUser.gender = 1;
                                }else if (map.get("gender").toString().equals("2")){
                                    sinaUser.gender = 2;
                                }else{
                                    sinaUser.gender = 0;
                                }
                                sinaUser.picUrl = map.get("profile_image_url").toString();
                                sinaUser.city = map.get("location").toString();

                                Toast.makeText(mContext, "您好，" + sinaUser.name, Toast.LENGTH_SHORT).show();
                                mUserController.saveUserInfo(sinaUser);
                                Intent intent = new Intent(mContext, MyInfoActivity.class);
                                startActivity(intent);
                                finish();
                            }else{
                                Log.d("TestData", "发生错误:"+status);
                            }
                        }
                    });
                }else{

                }
            }

            @Override
            public void onError(SocializeException e, SHARE_MEDIA share_media) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {

            }
        });

    }

    /**
     * 登录参数校验
     * @return false || true
     */
    public boolean LoginCheck() {
        if (!CharCheckUtil.isPhoneNum(mPhoneET.getText().toString())){
            showToast("您输入的手机号码有误，请重新输入!");
            return false;
        }
        if (!CharCheckUtil.isAllDigit(mCodeET.getText().toString())){
            showToast("您输入的验证码有误，请重新输入!");
            return false;
        }
        return true;
    }

    /**
     *  如果有使用任一平台的SSO授权, 则必须在对应的activity中实现onActivityResult方法, 并添加如下代码
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 根据requestCode获取对应的SsoHandler
        UMSsoHandler ssoHandler = mShareUtils.getmController().getConfig().getSsoHandler(resultCode);
        if (ssoHandler != null){
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

    @Override
    protected void obtainInfo() {

    }
}
